package core

import (
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"os"
	"strings"
)

type ProjShellFileList struct {
	PlgBase
	homedir string
}

/*
*

	{
	  "id":"sd-pickup",
	  "type":"core.shell.filelist",
	  "conf":{
	    "home":"/home"
	  }
	}
*/
func (this *ProjShellFileList) ReloadConf(conf *wrapper.SuperValue) error {
	conf.CheckExistsStrFunc("home", func(strv string) {
		this.homedir = strv
		if !strings.HasSuffix(this.homedir, "/") && strings.HasSuffix(this.homedir, "\\") {
			this.homedir += utils.PathSeparator
		}
	})
	return nil
}

func (this *ProjShellFileList) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {

	}
	return
}

/*
*

	?path=/xxxx/xxx&tag=0

tag:0 所有

	1: 只列出文件夹
	2: 只列出文件
*/
func (this *ProjShellFileList) OnHttpDo(rec *PlgHttpRec) (rval interface{}, errcode int, err error) {
	if len(this.homedir) == 0 {
		rec.ResponseJSONValues("code", -1, "errcode", 404, "msg", "没有指定主路径！")
		return
	}
	tag := rec.QryAsInt("tag", 0)
	str := rec.QryAsString("path", "")
	str = strings.TrimPrefix(str, "/")
	str = strings.TrimPrefix(str, "\\")
	strPath := this.homedir + str + utils.PathSeparator
	lst := rec.Resp.ForceByPath("list")
	utils.RangeFiles(strPath, 1, func(path string, f os.FileInfo) bool {
		if tag > 0 {
			if f.IsDir() {
				if tag != 1 {
					return true
				}
			} else {
				if tag != 2 {
					return true
				}
			}
		}

		rec := lst.AppendObject()
		//fname := path + f.Name()
		//fname = strings.TrimPrefix(fname, this.homedir)
		fname := f.Name()
		rec.SetKeyValues("name", fname)
		if f.IsDir() {
			rec.SetKeyValue("dir", 1)
		} else {
			rec.SetKeyValue("last-modify", f.ModTime())
			rec.SetKeyValue("size", f.Size())
		}
		return true
	}, nil)

	rec.ResponseAsJSON()
	return
}

// /// plug/path
// func (this *ProjShellFileList) OnHttpIndex(rec *PrjHttpRec) (rval interface{}, errcode int, err error) {

// }

func CreateProjShellFileListFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &ProjShellFileList{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}
